// src/stores/base/menuStore.ts
import userApi from "@/api/system/user";
import { changeTree } from "@/utils";
import { defineStore } from "pinia";
import { Router } from "vue-router";
import menuList from "@/router/menuList"

// 使用 import.meta.glob 预加载所有视图组件
const modules = import.meta.glob("@/views/**/*.vue");

const useMenuStore = defineStore("menu", {
  state: (): {
    menusList: MenuItem[];
    menus: SysMenu[];
    loading: boolean;
  } => ({
    // 菜单列表
    menusList: [],
    menus: [],
    loading: false,
  }),

  actions: {
    setMenus(data: MenuItem[]) {
      this.menus = data;
    },

    getMenus() {
      return this.menus;
    },

    setMenuList(data: any) {
      this.menusList = data;
    },

    getMenuList() {
      return this.menusList;
    },

    // 获取菜单并添加路由
    async fetchMenusAndRoutes(router: Router) {
      try {
        this.loading = true;
        const res: any = await userApi.getUserMenus();
        this.setMenus(res);
        this.setMenuList(processMenuData(res));
        processAndAddRoutes(res, router);
        return res;
      } catch (error) {
        console.error("获取菜单和添加路由失败:", error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
  },

  persist: {
    key: "persistent_menu_store",
    storage: localStorage,
  },
});

// 处理菜单渲染侧边栏
function processMenuData(menuData: SysMenu[]) {
  const menu = menuData.map((item: SysMenu) => {
    // 构造组件路径
    let path = item.path;
    if (item.menuType == "C") {
      path = getFullPath(menuData, item.id!);
    }
    return {
      id: item.id,
      parentId: item.parentId,
      key: item.id,
      title: item.menuName,
      path,
      // 从预加载的模块中获取组件
      meta: {
        type: item.menuType == "M" ? 1 : 2,
        key: item.id,
        name: item.menuName,
      },
    };
  });
  const tree = [
    ...menuList,
    ...changeTree(menu, "0"),
  ];
  return tree
}

// 处理菜单数据并动态添加路由
function processAndAddRoutes(menuData: SysMenu[], router: Router) {
  try {
    const preTree = menuData
      .filter((item: SysMenu) => item?.component && item?.path)
      .map((item: SysMenu) => {
        // 构造组件路径
        const componentPath = `/src/views/${item.component}.vue`;
        const path = getFullPath(menuData, item.id!);
        return {
          ...item,
          path,
          // 从预加载的模块中获取组件
          component: modules[componentPath],
          meta: {
            type: item.menuType == "M" ? 1 : 2,
            key: item.id,
            name: item.menuName,
          },
        };
      });

    preTree.forEach((item: any) => {
      router.addRoute("layout", item);
    });
  } catch (error) {
    console.error(error);
  }
}

// 根据菜单ID递归获取完整路径
function getFullPath(menuData: SysMenu[], targetId: string): string {
  // 查找目标菜单项
  const targetItem = menuData.find((item) => item.id == targetId);

  // 如果找不到目标项或路径为空，返回空字符串
  if (!targetItem || !targetItem.path) {
    return "";
  }

  // 如果是根节点(parentId为0)，直接返回路径
  if (targetItem.parentId === 0) {
    return `/${targetItem.path}`;
  }

  // 查找父级菜单项
  const parentItem = menuData.find((item) => item.id === targetItem.parentId);

  // 如果找不到父级项，返回当前路径
  if (!parentItem) {
    return `/${targetItem.path}`;
  }

  // 递归获取父级完整路径并拼接当前路径
  return `${getFullPath(menuData, parentItem.id!)}/${targetItem.path}`;
}

export default useMenuStore;
